﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using LiBLaB.Networking.Asynchronous;
using LiBLaB.GUI;
using LiBLaB.IImage;

namespace AsyncClient
{
    
    public partial class ClientMainFrm : Form
    {
        Client client;
        static GUI gui;

        public ClientMainFrm()
        {
            InitializeComponent();
            
            client = new Client();
            gui = new GUI();
        }

        void ButtonConnectOnClick(object obj, EventArgs ea)
        {
            Listbox1.Items.Add("Connecting...");
            string server_ip = textBox1.Text.Split(':')[0];
            int server_port = int.Parse(textBox1.Text.Split(':')[1]);
            client.Connect(server_ip, server_port, connectionEstablished);
        }

        void connectionEstablished(bool status)
        {
            if (status)
                gui.AddToGUI(this, Listbox1, "Connected to: " + client.ServerIP);
            else
                gui.AddToGUI(this, Listbox1, "Failed to connect to: " + client.ServerIP);
        }

        void ButtonSendOnClick(object obj, EventArgs ea)
        {
            byte[] message = Encoding.ASCII.GetBytes(newText.Text);
            newText.Clear();
            client.Send(message);
            client.Receive(dataReceived);
        }

        void dataReceived(byte[] buffer)
        {
            if (buffer.Length < 40)
            {
                string message = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
                gui.AddToGUI(this, Listbox1, message);
            }
            else
            {
                pictureBox1.Image = IImage.ImageFromStream(buffer);
            }
        }

        void ButtonDisconOnClick(object obj, EventArgs ea)
        {
            client.Dissconnect();
            Listbox1.Items.Add("Disconnected");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Listbox1.Items.Clear();
        }
    }
}